import React, { Component } from 'react';
import { Radio, DatePicker } from 'antd';
import PropTypes from 'prop-types';
import moment from 'moment';

class RunAtTimePicker extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isRunAt: 'now',
      time: '',
      disableTime: moment()
    };
  }

  onRunAtChange = () => {
    const { onChange } = this.props;
    const { isRunAt, time } = this.state;
    let formatTime = moment(time).format('YYYY-MM-DD HH:mm');
    if (isRunAt === 'now') {
      formatTime = moment().format('YYYY-MM-DD HH:mm');
    }
    onChange({
      isRunAt: !(isRunAt === 'now'),
      time: formatTime
    });
  };

  onTimeRadioChange = e => {
    this.setState({ isRunAt: e.target.value }, this.onRunAtChange);
  };

  onDatePickerChange = time => {
    this.setState({ time, disableTime: time }, this.onRunAtChange);
  };

  range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  disabledDateTime = () => {
    let { disableTime } = this.state;
    let hours = moment().hours();
    let minutes = moment().minutes();
    disableTime = disableTime ? disableTime : moment();
    if (disableTime.date() === moment().date()) {
      if (disableTime.hours() > hours) {
        if (minutes + 5 > 60 && disableTime.hours() - hours === 1) {
          minutes = minutes - 55; // minutes + 5 - 60
        } else {
          minutes = 0;
        }
        return {
          disabledHours: () => this.range(0, hours),
          disabledMinutes: () => this.range(0, minutes)
        };
      }
      // TODO: 目前固定只能选5分钟后，后续可以改为传参指定
      minutes += 5;
      return {
        disabledHours: () => this.range(0, hours),
        disabledMinutes: () => this.range(0, minutes)
      };
    }
  };

  render() {
    const { isRunAt } = this.state;
    return (
      <div>
        <div style={{ marginBottom: 16 }} className="run-at-name">
          执行时间
        </div>
        <Radio.Group onChange={this.onTimeRadioChange} value={isRunAt}>
          <Radio value="now" style={{ marginRight: 50 }} className="run-at-now">
            立即
          </Radio>
          <Radio value="appoint">指定时间</Radio>
        </Radio.Group>
        <DatePicker
          onChange={this.onDatePickerChange}
          showTime={{ defaultValue: moment().add(5, 'm'), format: 'HH:mm' }}
          disabledDate={current => {
            return current && current < moment().startOf('day');
          }}
          disabledTime={this.disabledDateTime}
          format="YYYY-MM-DD HH:mm"
          placeholder={'请选择时间'}
          disabled={isRunAt !== 'appoint'}
          style={{ minWidth: 150, width: 150 }}
          showToday={false}
        />
      </div>
    );
  }
}

RunAtTimePicker.propTypes = {
  onChange: PropTypes.function,
  runAt: PropTypes.object
};

export default RunAtTimePicker;
